package com.example.dw.model;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DwModel {

    private DataSource dataSource;

    private String dsNo;

    public DwModel(DataSource dataSource, String dsNo) {
        this.dataSource = dataSource;
        this.dsNo = dsNo;
    }

    /**
     * 查询表的字段信息
     */
    public List<Map<String, Object>> getTableColumns(String tableName) {
        Connection conn = null;
        ResultSet rs = null;
        List<Map<String, Object>> columns = new ArrayList<>();

        try {
            conn = getConnection();
            DatabaseMetaData metaData = conn.getMetaData();

            String catalog = conn.getCatalog();
            String schema = conn.getSchema();

            rs = metaData.getColumns(catalog, schema, tableName, "%");

            while (rs.next()) {
                Map<String, Object> column = new LinkedHashMap<>();
                column.put("columnName", rs.getString("COLUMN_NAME"));
                column.put("dataType", rs.getString("TYPE_NAME"));
                column.put("columnSize", rs.getInt("COLUMN_SIZE"));
                column.put("decimalDigits", rs.getInt("DECIMAL_DIGITS"));
                column.put("isNullable", rs.getInt("NULLABLE"));
                column.put("remarks", rs.getString("REMARKS"));
                column.put("columnDefault", rs.getString("COLUMN_DEF"));
                column.put("autoIncrement", rs.getString("IS_AUTOINCREMENT"));

                columns.add(column);
            }

        } catch (SQLException e) {
            throw new RuntimeException("查询表字段失败: " + tableName, e);
        } finally {
            closeResultSet(rs);
            closeConnection(conn);
        }

        return columns;
    }

    /**
     * 获取数据库连接
     */
    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     */
    private void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭语句
     */
    private void closeStatement(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭结果集
     */
    private void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
